package com.hyc.server;


import com.hyc.server.netty.nettyInitializer.NettyServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 冷环渊
 * @date 2025/3/22 16:54
 * @description NettyRpcServer
 */
public class NettyServer {

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();


    public void start(int port) {
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer());
        try {
            ChannelFuture future = serverBootstrap.bind(port).sync();
            // 将关闭通道的方式 也设置为异步的
            //    阻塞finally中的代码执行
            System.out.println("netty服务器启动");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyServer nettyServer = new NettyServer();
        nettyServer.start(9999);
    }
}
